<?php

declare(strict_types=1);

namespace app\sys\controller;

use app\sys\service\syncService;
use app\sys\service\SystemMenuService;
use Exception;
use think\admin\Controller;
use think\admin\model\SysIndustry;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\HttpResponseException;


/**
 * 行业分类管理
 * class Industry
 * @package app\sys\controller
 */
class Industry extends Controller
{
    /**
     * 行业分类分页列表
     * @auth true
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function page()
    {
        $query = SysIndustry::mQuery();
        $query->where(['is_deleted' => 0]);
        // 数据列表搜索过滤
        $query->equal('status,parent_id')->dateBetween('create_time');
        $query->like('title');
        $query->dataScope('created_by');
        $lists = $query->order('sort desc,id asc')->page(false, false, false);
        if (count($lists['list']) > 0) $lists['list'] = SystemMenuService::instance()->toTree($lists['list']);
        $this->success('数据获取成功', $lists['list']);
    }

    /**
     * 行业分类列表
     * @login true
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list()
    {
        $lists = SysIndustry::mk()
            ->where(['is_deleted' => '0', 'status' => 0])
            ->order('id DESC')
            ->select()
            ->toArray();
        $this->success('数据获取成功', $lists['list']);
    }

    /**
     * 获取分类选择树
     * @login true
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function tree()
    {
        $trees = SysIndustry::mk()
            ->where(['is_deleted' => 0])
            ->where(['status' => 0])
            ->field('id,parent_id,title,id as value')
            //->field('id,parent_id,name as label')
            ->order('sort desc')
            ->select()
            ->toArray();
        $lists = SystemMenuService::instance()->toTree($trees);
        $this->success('数据获取成功', $lists);
    }

    /**
     * 获取一条单页详情
     * @auth true
     * @return void
     */
    public function detail()
    {
        sysoplog('行业分类管理', '行业分类详情获取成功');
        $this->success('操作成功', SysIndustry::detail($this->request->param('id')));
    }

    /**
     * 添加行业分类
     * @auth true
     * @return void
     */
    public function add()
    {
        sysoplog('行业分类管理', '新增行业分类');
        SysIndustry::mForm('form');
    }

    /**
     * 编辑行业分类
     * @auth true
     * @return void
     */
    public function edit()
    {
        sysoplog('行业分类管理', '编辑行业分类');
        SysIndustry::mForm('form');
    }

    /**
     * 同步行业分类
     * @auth true
     * @return void
     */
    public function sync()
    {
        try {
            $result = syncService::syncData('sync/industry');
            if (empty($result['code'])) $this->error($result['info']);
            set_time_limit(100);
            foreach ($result['data'] as $vo) SysIndustry::mUpdate(['industry_id' => $vo['industry_id'], 'parent_id' => $vo['parent_id'], 'title' => $vo['title'], 'desc' => $vo['desc'], 'standard' => $vo['standard'], 'standard_no' => $vo['standard_no'], 'standard_file' => $vo['standard_file'], 'is_deleted' => 0], 'industry_id');
            $this->success('同步行业分类成功！');
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (Exception $exception) {
            $this->error('同步行业分类数据失败！');
        }
    }

    /**
     * 修改状态
     * @auth true
     * @return void
     */
    public function state()
    {
        sysoplog('分类管理', '修改分类状态');
        SysIndustry::mSave($this->_vali([
            'status.in:0,1' => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除行业分类
     * @auth true
     * @return void
     */
    public function delete()
    {
        $id = $this->request->param('id');//input('id');
        $ids = explode(',', $id);

        if ($this->checkChildrenExists($ids)) {
            $this->error('您要删除的分类下还有下级分类，如需删除请先删除下级分类后再删除该分类。');
        } else {
            sysoplog('分类管理', '删除分类');
            SysIndustry::mSave(['is_deleted' => 1, 'status' => 1], 'id', [['id', 'in', $ids]]);
        }
    }

    /**
     * 检查子分类是否存在
     * @param array $ids
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function checkChildrenExists(array $ids): bool
    {
        if (SysIndustry::mk()->whereIn('parent_id', $ids)->where(['is_deleted' => 0])->find()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 表单数据处理
     * @param array $data
     * @return void
     */
    protected function _form_filter(array &$data)
    {
        if (!empty($data['id']) && $data['id'] === $data['parent_id']) {
            $this->error('上级分类不能为本分类');
        }
    }

}
